package io.gitee.mingbaobaba.apijson.querycondition.query.dao.support;

import io.gitee.mingbaobaba.apijson.querycondition.query.exception.ConditionException;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>端点解析工具</p>
 *
 * 用于在多端点配置中挑选可用地址。
 */
public final class EndpointResolver {

    private EndpointResolver() {
    }

    public static String pickOne(String endpoints, Random random) {
        List<String> endpointList = Stream.of(StringUtils.defaultString(endpoints).split(","))
                .map(String::trim)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());
        if (endpointList.isEmpty()) {
            throw new ConditionException("服务地址未配置");
        }
        if (endpointList.size() == 1) {
            return endpointList.get(0);
        }
        int idx = random.nextInt(endpointList.size());
        return endpointList.get(idx);
    }
}

